package com.asen.test.view

import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Route
import com.asen.app.router.ActivityPath
import com.asen.libcommon.base.extend.extRefreshFinish
import com.asen.libcommon.base.extend.extImmersionBar
import com.asen.libcommon.base.viewbind.BaseViewBindActivity
import com.asen.libcommon.base.viewbind.viewBind
import com.asen.test.databinding.ActivityViewPager2Binding
import com.asen.test.view.pager.Drawer1
import com.asen.test.view.pager.Drawer2
import com.asen.test.view.pager.Drawer3
import com.orhanobut.logger.Logger
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * @author : asenLiang
 * @date   : 2021/03/25
 * @e-mail : liangAisiSen@163.com
 * @desc   : ViewPager2学习，分页加载，可用户仿抖音列表，只要添加视频播放控件在里面便可
 */
@Route(path = ActivityPath.TestModule.ViewPager2Activity)
class ViewPager2Activity : BaseViewBindActivity<ActivityViewPager2Binding>() {

    override val mBinding: ActivityViewPager2Binding by viewBind()

    // 持有强引用，不要把Fragment放再列表里面，会导致内存泄漏
    private var mDate = getDate()

    override suspend fun initView() {
        extImmersionBar()
        mBinding.apply {
            viewPager.orientation = ViewPager2.ORIENTATION_VERTICAL
            viewPager.adapter = object : FragmentStateAdapter(this@ViewPager2Activity) {
                override fun getItemCount(): Int = mDate.size
                override fun createFragment(position: Int): Fragment {
                    return when (mDate[position]) {
                        "0" -> Drawer1()
                        "1" -> Drawer2()
                        else -> Drawer3()
                    }
                }
            }

            viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
                override fun onPageSelected(position: Int) {
                    Logger.e("滑动页 >> $position")
                }
            })

            // todo：加载更多监听
            mSmartRefreshLayout.setOnLoadMoreListener {
                lifecycleScope.launch {
                    it.extRefreshFinish(false)
                    delay(timeMillis = 1000)
                    mDate.addAll(getDate())
                    (viewPager.adapter as FragmentStateAdapter).notifyDataSetChanged()
                }
            }

            // todo：刷新监听
            mSmartRefreshLayout.setOnRefreshListener {
                mDate = getDate()
                (viewPager.adapter as FragmentStateAdapter).notifyDataSetChanged()
                it.extRefreshFinish(true)
            }

        }
    }

    private fun getDate(): MutableList<String> {
        return mutableListOf<String>().apply {
            for (i in 0 until 6) {
                add("${i % 3}")
            }
        }
    }
}